<template>
  <div class="register">
    <div class="register-container">
      <!-- 左侧信息区 -->
      <div class="register-left">
        <div class="system-info">
          <h2 class="system-title">多氟多产业供应链系统</h2>
          <p class="system-subtitle">专业·高效·智能</p>

          <div class="steps-container">
            <div class="step-item">
              <div class="step-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="step-content">
                <h4>账号注册</h4>
                <p>创建您的供应链系统账号</p>
              </div>
            </div>
            <div class="step-divider"></div>
            <div class="step-item">
              <div class="step-icon">
                <i class="el-icon-folder-checked"></i>
              </div>
              <div class="step-content">
                <h4>资质认证</h4>
                <p>提交企业资质进行认证</p>
              </div>
            </div>
            <div class="step-divider"></div>
            <div class="step-item">
              <div class="step-icon">
                <i class="el-icon-s-cooperation"></i>
              </div>
              <div class="step-content">
                <h4>开始使用</h4>
                <p>加入产业链生态开展业务</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧注册表单 -->
      <div class="register-right">
        <div class="register-form-wrapper">
          <h3 class="form-title">账号注册</h3>
          <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号">
                <i slot="prefix" class="el-input__icon el-icon-user"></i>
              </el-input>
              <div class="username-tips">账号只能包含字母和数字，长度2-20位</div>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-lock"></i>
              </el-input>
              <div class="password-tips">密码须包含大小写字母、数字和特殊字符(@$!%*?&)，长度8-20位，且不能包含连续三个及以上的数字或字母</div>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                auto-complete="off"
                placeholder="确认密码"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-key"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="phonenumber">
              <el-input
                v-model="registerForm.phonenumber"
                type="text"
                auto-complete="off"
                placeholder="手机号"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-mobile-phone"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                type="email"
                auto-complete="off"
                placeholder="邮箱"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-message"></i>
                <el-button slot="append" @click="handleSendCode" :disabled="codeButtonDisabled">
                  {{ codeButtonText }}
                </el-button>
              </el-input>
            </el-form-item>

            <el-form-item prop="verifyCode">
              <el-input
                v-model="registerForm.verifyCode"
                type="text"
                auto-complete="off"
                placeholder="验证码"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-key"></i>
              </el-input>
            </el-form-item>

            <el-form-item prop="roleIds">
              <el-select
                v-model="registerForm.roleIds"
                placeholder="请选择角色"
                class="role-select">
                <template slot="prefix">
                  <i class="el-icon-user-solid"></i>
                </template>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1">
                  <span style="float: left">
                    <i :class="item.roleId === 101 ? 'el-icon-s-shop' : 'el-icon-shopping-cart-2'"></i>
                    {{ item.roleName }}
                  </span>
                  <span style="float: right; color: #8c8c8c; font-size: 12px">{{ item.description }}</span>
                </el-option>
              </el-select>
              <div class="role-tips">请选择您的角色类型</div>
            </el-form-item>

            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="registerForm.code"
                auto-complete="off"
                placeholder="验证码"
                class="captcha-input"
                @keyup.enter.native="handleRegister">
                <i slot="prefix" class="el-input__icon el-icon-picture-outline"></i>
              </el-input>
              <div class="register-code">
                <img :src="codeUrl" @click="getCode" class="register-code-img"/>
              </div>
            </el-form-item>

            <el-form-item class="agreement-item">
              <el-checkbox v-model="agreement">我已阅读并同意<a href="javascript:;">《服务协议》</a>和<a href="javascript:;">《隐私政策》</a></el-checkbox>
            </el-form-item>

            <el-form-item class="register-btn-item">
              <el-button
                :loading="loading"
                type="primary"
                class="register-btn"
                :disabled="!agreement"
                @click.native.prevent="handleRegister">
                <span v-if="!loading">立即注册</span>
                <span v-else>注册中...</span>
              </el-button>
            </el-form-item>

            <div class="login-option">
              已有账号？<router-link class="login-link" :to="'/login'">直接登录</router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register, registerFromInfo } from "@/api/login";
import request from '@/utils/request'

export default {
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    const validateEmail = (rule, value, callback) => {
      const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailPattern.test(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    };

    // 添加密码校验规则，禁止连续三个及以上的数字或字母
    const validatePassword = (rule, value, callback) => {
      // 检查是否包含连续三个及以上的数字
      if (/\d{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的数字"));
        return;
      }

      // 检查是否包含连续三个及以上的小写字母
      if (/[a-z]{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的小写字母"));
        return;
      }

      // 检查是否包含连续三个及以上的大写字母
      if (/[A-Z]{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的大写字母"));
        return;
      }

      callback();
    };

    return {
      codeUrl: "",
      agreement: false, // 新增用户协议勾选项
      roleOptions: [
        {
          roleId: 101,
          roleName: "供应商",
          roleKey: "supplier",
          description: "提供产品和服务的企业或个人"
        },
        {
          roleId: 102,
          roleName: "采购商",
          roleKey: "purchase",
          description: "采购产品和服务的企业或个人"
        }
      ],
      registerForm: {
        roleIds: [],
        phonenumber: "",
        email: "",
        username: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        verifyCode: "", // 新增邮箱验证码字段
      },
      registerRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]+$/, message: '账号只能包含字母和数字，不能包含特殊字符', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 8, max: 20, message: "密码长度必须介于 8 和 20 之间", trigger: "blur" },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
            message: "密码必须包含大小写字母、数字和特殊字符",
            trigger: "blur"
          },
          { validator: validatePassword, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入您的手机号" },
          {pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,message:"手机号格式不正确",trigger:"blur"}
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入您的邮箱" },
          { validator: validateEmail, trigger: "blur" }
        ],
        roleIds:[{ required: true, trigger: "blur", message: "请选择您的角色类型（供应商或采购商）" }],
        verifyCode: [{ required: true, trigger: "blur", message: "请输入邮箱验证码" }]
      },
      loading: false,
      captchaEnabled: true,
      // 邮箱验证码相关
      codeButtonDisabled: false,
      codeButtonText: "获取验证码",
      countdown: 60
    };
  },
  created() {
    this.getCode();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.registerForm.uuid = res.uuid;
        }
      });
    },
    // 发送邮箱验证码
    handleSendCode() {
      // 只验证邮箱字段
      this.$refs.registerForm.validateField('email', (errorMessage) => {
        if (errorMessage) {
          return;
        }

        this.codeButtonDisabled = true;
        this.countdown = 60;
        this.codeButtonText = `${this.countdown}秒后重试`;

        // 发送验证码请求
        request({
          url: '/system/user/sendEmail',
          method: 'post',
          params: {
            email: this.registerForm.email
          }
        }).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '发送成功',
              message: '验证码已发送到您的邮箱',
              type: 'success',
              duration: 1500,
              position: 'top-right',
              customClass: 'register-notify'
            });
            this.startCountdown();
          } else {
            this.$notify({
              title: '发送失败',
              message: res.msg || '验证码发送失败',
              type: 'error',
              duration: 1500,
              position: 'top-right',
              customClass: 'register-notify'
            });
            this.codeButtonDisabled = false;
            this.codeButtonText = '获取验证码';
          }
        }).catch(() => {
          this.$notify({
            title: '发送失败',
            message: '验证码发送失败',
            type: 'error',
            duration: 1500,
            position: 'top-right',
            customClass: 'register-notify'
          });
          this.codeButtonDisabled = false;
          this.codeButtonText = '获取验证码';
        });
      });
    },

    // 开始倒计时
    startCountdown() {
      const timer = setInterval(() => {
        this.countdown--;
        this.codeButtonText = `${this.countdown}秒后重试`;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.codeButtonDisabled = false;
          this.codeButtonText = '获取验证码';
        }
      }, 1000);
    },

    handleRegister() {
      if (!this.agreement) {
        this.$notify({
          title: '提示',
          message: '请阅读并同意服务协议和隐私政策',
          type: 'warning',
          duration: 1500,
          position: 'top-right',
          customClass: 'register-notify'
        });
        return;
      }

      // 额外验证用户名格式，防止SQL注入
      const usernamePattern = /^[a-zA-Z0-9]+$/;
      if (!usernamePattern.test(this.registerForm.username)) {
        this.$notify({
          title: '格式错误',
          message: '账号只能包含字母和数字，不能包含特殊字符',
          type: 'error',
          duration: 1500,
          position: 'top-right',
          customClass: 'register-notify'
        });
        return;
      }

      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;

          // 先验证邮箱验证码
          request({
            url: '/system/user/verifyCode',
            method: 'post',
            params: {
              email: this.registerForm.email,
              code: this.registerForm.verifyCode
            }
          }).then(res => {
            if (res.code === 200) {
              // 验证码正确，继续注册流程
              const submitData = {
                ...this.registerForm,
                roleIds: Array.isArray(this.registerForm.roleIds)
                  ? this.registerForm.roleIds
                  : [this.registerForm.roleIds]
              };

              return registerFromInfo(submitData);
            } else {
              this.$notify({
                title: '验证失败',
                message: res.msg || '验证码验证失败',
                type: 'error',
                duration: 1500,
                position: 'top-right',
                customClass: 'register-notify'
              });
              throw new Error(res.msg || '验证码验证失败');
            }
          }).then(res => {
            const username = this.registerForm.username;
            this.$notify({
              title: '注册成功',
              message: `恭喜您，账号 ${username} 注册成功！`,
              type: 'success',
              duration: 1500,
              position: 'top-right',
              customClass: 'register-notify'
            });
            setTimeout(() => {
              this.$router.push("/login");
            }, 2000);
          }).catch(error => {
            // 处理错误信息
            let errorMessage = "操作失败，请稍后重试";
            if (error.response && error.response.data && error.response.data.message) {
              errorMessage = error.response.data.message;
            } else if (typeof error === "string") {
              errorMessage = error;
            } else if (error.message) {
              errorMessage = error.message;
            }
            this.$notify({
              title: '注册失败',
              message: errorMessage,
              type: 'error',
              duration: 1500,
              position: 'top-right',
              customClass: 'register-notify'
            });
          }).finally(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/RegisterBG.jpg");
  background-size: cover;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
  }

  .register-container {
    display: flex;
    width: 1000px;
    min-height: 600px;
    border-radius: 10px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    position: relative;
    z-index: 2;

    .register-left {
      width: 40%;
      background: linear-gradient(135deg, #52c41a, #1a9d55);
      padding: 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .system-info {
        color: #fff;

        .system-title {
          font-size: 26px;
          font-weight: 600;
          margin-bottom: 15px;
        }

        .system-subtitle {
          font-size: 16px;
          opacity: 0.9;
          margin-bottom: 60px;
        }

        .steps-container {
          margin-top: 20px;

          .step-item {
            display: flex;
            align-items: center;
            margin-bottom: 30px;

            .step-icon {
              width: 50px;
              height: 50px;
              border-radius: 50%;
              background: rgba(255, 255, 255, 0.15);
              display: flex;
              justify-content: center;
              align-items: center;
              margin-right: 15px;
              flex-shrink: 0;

              i {
                font-size: 24px;
                color: #fff;
              }
            }

            .step-content {
              h4 {
                font-size: 18px;
                margin: 0 0 5px;
                font-weight: 500;
              }

              p {
                margin: 0;
                font-size: 14px;
                opacity: 0.8;
              }
            }
          }

          .step-divider {
            width: 2px;
            height: 25px;
            background: rgba(255, 255, 255, 0.2);
            margin-left: 25px;
            margin-bottom: 5px;
          }
        }
      }
    }

    .register-right {
      width: 60%;
      background: #fff;
      padding: 40px;
      overflow-y: auto;

      .register-form-wrapper {
        max-width: 450px;
        margin: 0 auto;

        .form-title {
          font-size: 24px;
          font-weight: 600;
          color: #333;
          margin-bottom: 30px;
          text-align: center;
        }

        .register-form {
          .el-form-item {
            margin-bottom: 20px;

            .el-input__inner {
              height: 44px;
              line-height: 44px;
              border-radius: 4px;
              padding-left: 42px;
              border: 1px solid #dcdfe6;

              &:focus {
                border-color: #52c41a;
                box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.15);
              }
            }

            .el-input__prefix {
              left: 10px;

              i {
                font-size: 18px;
                color: #909399;
              }
            }
          }

          .captcha-input {
            width: 65%;
            float: left;
          }

          .role-select {
            width: 100%;

            .el-input__inner {
              padding-left: 42px;
            }

            .el-input__prefix {
              left: 10px;

              i {
                font-size: 18px;
                color: #909399;
              }
            }
          }

          .register-code {
            width: 32%;
            float: right;

            .register-code-img {
              height: 44px;
              width: 100%;
              cursor: pointer;
              vertical-align: middle;
              border-radius: 4px;
            }
          }

          .agreement-item {
            margin-top: 10px;
            margin-bottom: 15px;

            .el-checkbox__label {
              color: #666;
              font-size: 14px;

              a {
                color: #52c41a;
                text-decoration: none;

                &:hover {
                  text-decoration: underline;
                }
              }
            }
          }

          .register-btn-item {
            margin-bottom: 15px;
          }

          .register-btn {
            width: 100%;
            height: 44px;
            font-size: 16px;
            font-weight: 500;
            background: #52c41a;
            border-color: #52c41a;

            &:hover:not(:disabled) {
              background: #73d13d;
              border-color: #73d13d;
            }

            &:disabled {
              background: #b8e39b;
              border-color: #b8e39b;
            }
          }

          .login-option {
            text-align: center;
            margin-top: 15px;
            color: #666;
            font-size: 14px;

            .login-link {
              color: #52c41a;
              text-decoration: none;

              &:hover {
                text-decoration: underline;
              }
            }
          }
        }
      }
    }
  }

  .el-register-footer {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    color: rgba(255, 255, 255, 0.7);
    font-size: 13px;
    z-index: 2;
  }

  .password-tips, .username-tips, .role-tips {
    font-size: 12px;
    color: #909399;
    line-height: 1.2;
    padding-top: 4px;
  }

  .el-input-group__append {
    padding: 0 15px;
    background-color: #52c41a;
    border-color: #52c41a;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #73d13d;
      border-color: #73d13d;
    }

    &:disabled {
      background-color: #b8e39b;
      border-color: #b8e39b;
      cursor: not-allowed;
    }
  }
}

/* 响应式适配 */
@media screen and (max-width: 992px) {
  .register {
    .register-container {
      width: 90%;
      flex-direction: column;

      .register-left {
        width: 100%;
        padding: 30px;

        .system-info {
          .system-title {
            font-size: 22px;
            text-align: center;
          }

          .system-subtitle {
            text-align: center;
            margin-bottom: 30px;
          }

          .steps-container {
            display: flex;
            justify-content: space-around;

            .step-item {
              flex-direction: column;
              text-align: center;
              margin-bottom: 0;

              .step-icon {
                margin-right: 0;
                margin-bottom: 10px;
              }
            }

            .step-divider {
              width: 50px;
              height: 2px;
              margin: 25px 0;
              transform: rotate(90deg);
              display: none;
            }
          }
        }
      }

      .register-right {
        width: 100%;

        .register-form-wrapper {
          max-width: 100%;
        }
      }
    }
  }
}

@media screen and (max-width: 576px) {
  .register {
    .register-container {
      .register-left {
        .system-info {
          .steps-container {
            flex-direction: column;

            .step-item {
              margin-bottom: 20px;
            }

            .step-divider {
              display: block;
              width: 2px;
              height: 25px;
              margin: 0 auto 20px;
              transform: none;
            }
          }
        }
      }
    }
  }
}

/* 注册通知样式 */
.register-notify {
  .el-notification__title {
    font-size: 16px;
    font-weight: bold;
  }
  .el-notification__content {
    font-size: 14px;
    margin: 8px 0;
  }
  &.el-notification--success {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
  }
  &.el-notification--error {
    background-color: #fef0f0;
    border-color: #fde2e2;
  }
  &.el-notification--warning {
    background-color: #fdf6ec;
    border-color: #faecd8;
  }
}
</style>
